
from rest_framework import views, status
from rest_framework.response import Response

from apps.app01.views.cart_add.serializers import AddToCartSerializer
from apps.app01.models import Cart, User, Product


class AddToCartView(views.APIView):


    def post(self, request):
        # 1. 使用序列化器校验前端传来的数据
        serializer = AddToCartSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    "code": 0,
                    "message": "添加购物车失败，参数有误",
                    "errors": serializer.errors
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 获取序列化后的数据
        product_id = serializer.validated_data["productId"]
        count = serializer.validated_data["count"]
        config = serializer.validated_data.get("config", [])

        # 3. 获取当前用户（假设已经做了登录，request.user即当前用户）
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # user = User.objects.first()  # 如果测试时需要，可临时写死

        # if user.is_anonymous:
        #     return Response(
        #         {"code": 0, "message": "用户未登录"},
        #         status=status.HTTP_401_UNAUTHORIZED
        #     )

        # 4. 确保商品存在 (序列化器已经做了检查，这里再取出商品对象)
        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            return Response(
                {"code": 0, "message": "商品不存在"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 5. 查询购物车中是否已存在同一款“商品 + 配置”的记录
        cart_item = Cart.objects.filter(
            user=user_id,
            product=product_obj,
            selected_configs=config
        ).first()

        if cart_item:
            # 已存在则叠加数量
            cart_item.count += count
            cart_item.save()
            new_count = cart_item.count
        else:
            # 不存在则创建新记录
            new_cart = Cart.objects.create(
                user=user_id,
                product=product_obj,
                count=count,
                selected_configs=config
            )
            new_count = new_cart.count

        # 6. 返回成功响应
        return Response(
            {
                "code": 1,
                "message": "ok",
                "count": new_count
            },
            status=status.HTTP_200_OK
        )
